#!/bin/bash

usage() {
    echo "usage:"
    echo "    bash build.sh TARGET_DIR"
    echo "examples:"
    echo "    bash build.sh ."
    echo "    bash build.sh samples/stm32u5a5_nucleo_multibin"
    echo ""
}

if [[ $# -lt 1 || ! -d "$1" ]]; then
    usage; exit
fi

target_dir="$1"
projects=$(find $target_dir -name *.prj)
log_file="build-error.log"

if [ -f "$log_file" ]; then
    rm -f $log_file
fi

for p in $projects; do
    pd=$(dirname $p)
    cd $pd
    echo "building $pd"
    make clean && make -j4 > /dev/null
    ret=$?
    cd - &> /dev/null
    if [ $ret -ne 0 ]; then
        echo "$pd" >> $log_file
    fi
done

if [ -f "$log_file" ]; then
    echo "build failed projects:"
    cat $log_file
fi
